<template>
    <view class="container">
        <view class="top-bg"></view>
        <view class="address">
            <view class="top">
                <view class="same-city" :class="{ active: order.delivery === 'same' }" @click="changeSame">
                    同城配送
                </view>
                <view class="self-pickup" :class="{ active: order.delivery === 'self' }" @click="changeSelf">
                    上门自提
                </view>
            </view>

            <view class="bottom">
                <view class="same" v-if="order.delivery === 'same'">
                    <view class="select-address" v-if="order.address === ''" @click="goAddress">
                        选择地址+
                    </view>
                    <view class="my-address" v-else>
                        <view class="info">
                            <view class="text">
                                <text class="name">{{ order.userName }}</text>
                                <text class="phone">{{ order.phone }}</text>
                            </view>
                            <text class="jiantou" @click="goAddress">&gt;</text>
                        </view>
                        <view class="detail">
                            {{ order.address }}
                        </view>
                    </view>
                </view>
                <view class="self" v-else>
                    <text class="phone">12341234123</text>
                    <text class="local">广东省 湛江市 麻章区 瑞康二横路37号</text>
                    <text class="time">营业时间：全天</text>
                </view>
            </view>

            <view class="borders">
                <view class="blue"></view>
                <view class="pink"></view>
                <view class="blue"></view>
                <view class="pink"></view>
                <view class="blue"></view>
                <view class="pink"></view>
                <view class="blue"></view>
                <view class="pink"></view>
                <view class="blue"></view>
                <view class="pink"></view>
                <view class="blue"></view>
                <view class="pink"></view>
            </view>
        </view>

        <!-- 下单的甜品信息 -->
        <view class="desserts">
            <view class="item" v-for="item in buyList" :key="item.id">
                <up-image :src="`http://localhost:8080/api/files/${
            item.dessert.dessertImg || ''
          }`" width="140rpx" height="140rpx"></up-image>
                <text class="name">{{ item.dessert.dessertName || '无' }}</text>
                <text class="specs">{{ item.dessert.specs || '无' }}</text>
                <text class="price">{{ '￥' + item.dessert.dessertPrice }}</text>
                <view class="option">
                    <text class="sub" @click="reduce(item)">-</text>
                    <text class="num">{{ item.num }}</text>
                    <text class="add" @click="add(item)">+</text>
                </view>
            </view>
        </view>

        <!-- 信息填写框 -->
        <view class="info">
            <!-- 门店信息 -->
            <view class="shop">
                <text class="name">门店信息</text>
                <text class="phone">16626566103</text>
            </view>
            <!-- 自提时间 -->
            <view class="takeTime" @click="openPop">
                <text class="sel">
                    {{ order.delivery === 'self' ? '自提时间' : '配送时间' }}
                </text>
                <view class="right">
                    <text class="timeText">{{ pickTime }}</text>
                    <text class="jiantou">&gt;</text>
                </view>
            </view>

            <!-- // 自提联系方式 -->
            <view class="name" v-if="order.delivery === 'self'">
                <text>联系人</text>
                <input type="text" placeholder="请输入联系人姓名" v-model="order.username" />
            </view>

            <view class="phone" v-if="order.delivery === 'self'">
                <text>联系手机号</text>
                <input type="text" placeholder="请输入联系人手机号" v-model="order.phone" />
            </view>

            <!-- 买家留言 -->
            <view class="msg">
                <text>买家留言</text>
                <input type="text" placeholder="请输入留言信息" v-model="order.message" />
            </view>
        </view>

        <!-- 优惠劵 -->
        <view class="coupons">
            <text>优惠劵</text>
            <view class="selcou" @click="couponShow = true">
                <text class="couname" v-if="Object.keys(coupon).length > 0">
                    {{ coupon.money }}元通用优惠劵
                </text>
                <text class="jiantou">&gt;</text>
            </view>
        </view>

        <up-picker :show="couponShow" :columns="couponColumn" keyName="label" @cancel="couponShow = false"
            @confirm="confirmCoupon"></up-picker>

        <!-- 支付方式 -->
        <view class="paytype">
            <text>支付方式</text>
            <view class="right">
                <text class="type">余额支付</text>
                <text class="jiantou">&gt;</text>
            </view>
        </view>

        <!-- 金额 -->
        <view class="money">
            <view class="count">
                <text class="zi">金额总计</text>
                <text class="amount">{{ '￥' + order.amount }}</text>
            </view>
            <view class="cou">
                <text class="zi">优惠劵</text>
                <text class="subs">-￥{{ coupon.money }}</text>
            </view>
        </view>

        <!-- 底部订单提交 -->
        <view class="footer">
            <view class="left">
                合计:
                <text class="money">{{ '￥' + order.amount }}</text>
            </view>
            <view class="right" @click="confirmBook">提交订单</view>
        </view>
    </view>
    <DatePicker ref="datePicker" @update-getTime="getTime" />
</template>

<script setup>
    import {
        onLoad,
        onShow
    } from '@dcloudio/uni-app'
    import {
        ref,
        nextTick
    } from 'vue'
    import {
        useUserStore
    } from '@/stores/user.js'
    import {
        useCartStore
    } from '@/stores/cart.js'
    import {
        addOrderService,
        addOrderDetailService
    } from '@/api/order.js'
    import {
        updateCoupon,
        delUserCoupon,
        getCouponService,
        getCouponDetail,
    } from '@/api/coupons.js'
    import {
        updateDessertService
    } from '@/api/dessert.js'
    import {
        batchDeleteCart,
        getCartByUserId
    } from '@/api/cart.js'
    import DatePicker from '@/components/DatePicker/DatePicker.vue'

    const userStore = useUserStore()
    const cartStore = useCartStore()

    const showPicker = ref(false)
    const order = ref({
        userId: userStore.userInfo.userId,
        amount: 0,
        username: '',
        phone: '',
        address: '',
        time: '',
        delivery: 'self',
        message: '',
        type: 'dessert',
        status: 1,
    })

    // 优惠劵
    const couponShow = ref(false)
    let couponList = ref([])
    let couponColumn = ref([])

    const datePicker = ref(null)
    const buyList = ref([])
    const fromCart = ref(true)
    onLoad((option) => {
        if (option.info) {
            // 立即购买或预订
            buyList.value.push(JSON.parse(decodeURIComponent(option.info)))
        } else {
            // 由购物车传递过来的
            buyList.value = JSON.parse(decodeURIComponent(option.buy))
        }

        // 计算总和
        order.value.amount = buyList.value
            .reduce((acc, curr) => {
                return acc + parseFloat(curr.dessert.dessertPrice) * curr.num
            }, 0)
            .toFixed(2)

        // 计算总数量
        order.value.count = buyList.value.reduce((acc, curr) => {
            return acc + curr.num
        }, 0)

        nextTick(() => {
            datePicker.value.getNextDay()
        })
    })

    onShow(async () => {
        couponColumn.value = []
        const res = await getCouponService(userStore.userInfo.userId)

        if (res.code == 0) {
            couponList.value = res.data ?? []
            // 构造数据添加到选择器中
            if (couponList.value.length > 0) {
                let column = ref([])
                couponList.value.map(async (item) => {
                    // 根据优惠劵ID获取优惠劵详情信息
                    const result = await getCouponDetail(item.couponsId)
                    if (result.code == 0) {
                        column.value.push({
                            label: `通用优惠劵${result.data.money}元`,
                            couponId: item.id,
                            money: result.data.money,
                            id: result.data.id,
                            count: item.count
                        })
                    }
                })
                couponColumn.value.push(column.value)
            }
        } else {
            couponColumn.value = []
        }
    })

    // 切换tab
    const changeSame = () => {
        couponColumn.value = couponColumn.value
        order.value.delivery = 'same'
    }

    const changeSelf = () => {
        couponColumn.value = couponColumn.value
        order.value.delivery = 'self'
    }

    // 确认选择优惠劵
    const coupon = ref({})
    const confirmCoupon = (e) => {
        coupon.value = {}
        couponShow.value = false
        const {
            value
        } = e
        coupon.value = {
            ...value[0]
        }
        if (Object.keys(coupon.value).length > 0) {
            order.value.amount = (
                parseFloat(order.value.amount) - parseInt(coupon.value.money)
            ).toFixed(2)
        }
    }

    // 总价格
    const getCount = () => {
        order.value.amount = buyList.value
            .reduce((acc, curr) => {
                return acc + parseFloat(curr.dessert.dessertPrice) * curr.num
            }, 0)
            .toFixed(2)
    }

    // 加甜品
    const add = async (item) => {
        let num = item.num
        item.num = num + 1
        getCount()
    }

    // 减甜品
    const reduce = async (item) => {
        let num = item.num
        if (num > 1) {
            num -= 1
        } else if ((num = 1)) {
            uni.showToast({
                title: '甜品数量不能少于1',
                icon: 'none',
            })
        }
        item.num = num
        getCount()
    }

    // 选择配送地址
    const select = ref(true)
    const goAddress = () => {
        uni.navigateTo({
            url: `/pages/myAddress/myAddress?select=${select}`,
        })
    }

    // 获取地址
    const getAddress = (address) => {
        order.value.username = address.name
        order.value.phone = address.phone
        order.value.address = address.address + address.houseNumber
    }

    // 选择配送时间
    // 打开时间选择器
    const openPop = () => {
        datePicker.value.showBox()
    }

    const pickTime = ref('')
    const getTime = (value) => {
        pickTime.value = value || ''
    }

    defineExpose({
        getAddress,
        order
    })

    // 下订单
    const dessertList = ref([])
    const confirmBook = async () => {
        order.value.time = pickTime.value
        // 发送请求新增订单
        order.value.status = order.value.delivery === 'self' ? '3' : '1'

        const res = await addOrderService(order.value)
        if (res.code === '0') {
            // 成功则发送请求新增订单详情
            order.value.time = ''

            // 遍历构造提交的甜品数据
            buyList.value.map((item) => {
                dessertList.value.push({
                    orderId: res.data.id,
                    dessertId: item.dessertId,
                    num: item.num,
                    total: parseFloat(
                        (item.num * parseFloat(item.dessert.dessertPrice)).toFixed(2)
                    ),
                })
            })

            const res11 = await addOrderDetailService(dessertList.value)

            if (res11.code === '0') {
                if (Object.getOwnPropertyNames(coupon.value).length > 0) {
                    // 优惠劵数量减一
                    coupon.value.count -= 1
                    if (coupon.value.count <= 0) {
                        // 删除表信息
                        await delUserCoupon(coupon.value.couponId)
                    } else {
                        // 修改优惠劵数量
                        const userCoupon = {
                            id: coupon.value.couponId,
                            userId: userStore.userInfo.userId,
                            couponsId: coupon.value.id,
                            count: coupon.value.count,
                        }
                        await updateCoupon(userCoupon)
                    }
                }

                // 当用户为普通用户时 如果总额大于30更新用户的身份为会员
                if (userStore.userInfo.member === 1) {
                    if (parseFloat(order.value.amount) >= 30) {
                        userStore.updateMember(2)
                    }
                }

                // 更新用户的积分
                if (userStore.userInfo.member === 2) {
                    const point =
                        userStore.userInfo.points +
                        Math.floor(parseInt(order.value.amount) / 2)
                    userStore.updatePoint(point)
                }

                // 更新用户余额
                const balance = parseFloat(
                    userStore.userInfo.balance - order.value.amount
                ).toFixed(2)
                userStore.updateBalance(balance)

                // 更新甜品销量与库存
                dessertList.value.map(async (item) => {
                    await updateDessertService(item.dessertId, item.num)
                })

                // 如果是购物车结算 则把商品移出购物车
                if (fromCart.value) {
                    const del = await batchDeleteCart(buyList.value)
                    if (del.code === '0') {
                        // 重新发送请求获取用户的购物车数据 更新到pinia中
                        const {
                            data
                        } = await getCartByUserId(userStore.userInfo.userId)
                        if (data) {
                            cartStore.setCar(data)
                            cartStore.setGoodsNum(data.length)
                        }
                    }
                }

                uni.showToast({
                    title: '创建订单成功',
                    icon: 'none',
                })

                // 跳转到我的订单页
                setTimeout(() => {
                    uni.redirectTo({
                        url: '/pages/myOrder/myOrder',
                    })
                }, 1000)
            } else {
                uni.showToast({
                    title: '订单提交失败',
                    icon: 'none',
                })
            }
        } else {
            uni.showToast({
                title: res.message,
                icon: 'none',
            })
            order.value.time = time
        }
    }
</script>

<style lang="scss" scoped>
    .container {
        width: 100%;
        height: 100%;
        background-color: #f1f1f1;
        overflow: auto;

        .top-bg {
            background-color: #f8e3b6;
            width: 100%;
            height: 200rpx;
        }

        .address {
            width: 95%;
            border-radius: 20rpx;
            background-color: #fff;
            margin: -200rpx auto 20rpx;

            .top {
                width: 100%;
                display: flex;
                background-color: #fff6f6;
                border-top-left-radius: 20rpx;
                border-top-right-radius: 20rpx;
                font-size: 38rpx;

                .same-city {
                    width: 50%;
                    text-align: center;
                    padding: 10rpx 0;
                }

                .self-pickup {
                    width: 50%;
                    text-align: center;
                    padding: 10rpx 0;
                }

                .active {
                    background-color: #fff;
                    border-top-right-radius: 40rpx;
                    border-top-left-radius: 40rpx;
                    font-weight: bold;
                    z-index: 11;
                    margin-top: -16rpx;
                    padding: 16rpx 0;
                }
            }

            .bottom {
                height: 200rpx;

                .self {
                    display: flex;
                    flex-direction: column;
                    padding: 18rpx;

                    .phone {
                        font-size: 34rpx;
                        font-weight: bold;
                        margin-bottom: 14rpx;
                    }

                    .local {
                        color: #6c6c6c;
                        font-size: 30rpx;
                        margin-bottom: 10rpx;
                    }

                    .time {
                        color: #6c6c6c;
                        font-size: 30rpx;
                        margin-bottom: 10rpx;
                    }
                }

                .same {
                    display: flex;
                    align-items: center;
                    justify-content: center;

                    .select-address {
                        padding: 20rpx 30rpx;
                        font-size: 30rpx;
                        border: 1px dotted #6c6c6c;
                        margin-top: 50rpx;
                    }

                    .my-address {
                        width: 100%;

                        .info {
                            font-size: 32rpx;
                            font-weight: bold;
                            padding: 10rpx 10rpx 0;
                            display: flex;
                            align-items: center;
                            justify-content: space-between;

                            .text {
                                display: flex;
                                align-items: center;
                            }

                            .jiantou {
                                font-size: 30rpx;
                                color: #787878;
                            }
                        }

                        .detail {
                            font-size: 28rpx;
                            color: #6c6c6c;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            margin-left: 10rpx;
                        }
                    }
                }
            }

            .borders {
                width: 100%;
                overflow: hidden;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .blue {
                    width: 36rpx;
                    height: 6rpx;
                    background-color: #98c2f3;
                }

                .pink {
                    width: 36rpx;
                    height: 6rpx;
                    background-color: #f6af99;
                }
            }
        }

        .desserts {
            width: 95%;
            border-radius: 20rpx;
            background-color: #fff;
            margin: 0 auto;

            .item {
                width: 100%;
                position: relative;
                padding: 10rpx;
                margin-bottom: 10rpx;

                .name {
                    font-size: 30rpx;
                    position: absolute;
                    top: 10rpx;
                    left: 170rpx;
                }

                .specs {
                    font-size: 26rpx;
                    color: #9d9d9d;
                    position: absolute;
                    top: 100rpx;
                    left: 170rpx;
                }

                .price {
                    color: #f6823e;
                    font-size: 28rpx;
                    position: absolute;
                    top: 10rpx;
                    right: 50rpx;
                }

                .option {
                    display: flex;
                    position: absolute;
                    bottom: 10rpx;
                    right: 30rpx;

                    text {
                        width: 60rpx;
                        line-height: 60rpx;
                        text-align: center;
                        display: inline-block;
                        background-color: #f1f1f1;
                        margin-right: 10rpx;
                    }

                    .add {
                        color: #787878;
                        font-weight: bold;
                        border-radius: 10rpx 30rpx 30rpx 10rpx;
                    }

                    .sub {
                        color: #787878;
                        font-weight: bold;
                        border-radius: 30rpx 10rpx 10rpx 30rpx;
                    }
                }
            }
        }

        .info {
            width: 95%;
            border-radius: 20rpx;
            background-color: #fff;
            padding: 30rpx 0;
            margin: 20rpx auto;

            .shop {
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-size: 30rpx;
                color: #222;
                font-weight: bold;
            }

            .takeTime {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 0 10rpx;
                margin-bottom: 20rpx;

                .sel {
                    font-size: 30rpx;
                    color: #222;
                    font-weight: bold;
                }

                .right {
                    display: flex;
                    align-items: center;

                    .timeText {
                        font-size: 28rpx;
                        color: #888;
                    }

                    .jiantou {
                        font-size: 30rpx;
                        color: #9d9d9d;
                    }
                }
            }

            .name {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 0 10rpx;
                margin-bottom: 20rpx;

                text {
                    font-size: 30rpx;
                    color: #222;
                    font-weight: bold;
                }

                input {
                    width: 150px;
                    height: 20rpx;
                    font-size: 28rpx;
                }
            }

            .phone {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 0 10rpx;
                margin-bottom: 20rpx;

                text {
                    font-size: 30rpx;
                    color: #222;
                    font-weight: bold;
                }

                input {
                    width: 150px;
                    height: 20rpx;
                    font-size: 28rpx;
                }
            }

            .msg {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 0 10rpx;

                text {
                    font-size: 30rpx;
                    color: #222;
                    font-weight: bold;
                }

                input {
                    width: 150px;
                    height: 20rpx;
                    font-size: 28rpx;
                }
            }
        }

        .coupons {
            width: 95%;
            border-radius: 20rpx;
            background-color: #fff;
            padding: 20rpx 0rpx 0rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin: 0 auto 20rpx;

            text {
                font-size: 30rpx;
                color: #222;
                font-weight: bold;
                margin-bottom: 30rpx;
                padding: 0 10rpx;
            }

            .selcou {
                display: flex;
                align-items: center;

                .couname {
                    color: #f6823e;
                }

                .jiantou {
                    color: #9d9d9d;
                }
            }
        }

        .paytype {
            width: 95%;
            border-radius: 20rpx;
            background-color: #fff;
            padding: 20rpx 0rpx 0rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin: 0 auto 20rpx;

            text {
                font-size: 30rpx;
                color: #222;
                font-weight: bold;
                margin-bottom: 30rpx;
                padding: 0 10rpx;
            }

            .right {
                display: flex;
                align-items: center;

                .type {
                    font-weight: bold;
                }

                .jiantou {
                    color: #9d9d9d;
                }
            }
        }

        .money {
            width: 95%;
            border-radius: 20rpx;
            background-color: #fff;
            padding: 20rpx 0rpx 10rpx;
            margin: 0 auto 120rpx;

            .count {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 0 10rpx;
                margin-bottom: 20rpx;

                .zi {
                    font-size: 30rpx;
                    color: #222;
                }

                .price {
                    font-size: 30rpx;
                    color: #000;
                    font-weight: bold;
                }
            }

            .cou {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 0 10rpx;
                margin-bottom: 20rpx;

                .zi {
                    font-size: 30rpx;
                    color: #222;
                }

                .subs {
                    font-size: 30rpx;
                    color: #f34b4a;
                    font-weight: bold;
                }
            }
        }

        .pay {
            width: 95%;
            border-radius: 20rpx;
            background-color: #fff;
            padding: 20rpx 0rpx;
            margin: 20rpx auto 60rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .zi {
                font-size: 30rpx;
                font-weight: bold;
                margin-left: 10rpx;
            }

            .sels {
                font-size: 28rpx;
            }

            .jiantou {
                font-size: 30rex;
                color: #787878;
                margin-right: 10rpx;
            }
        }

        .undisplay {
            display: none;
        }

        .footer {
            width: 100%;
            padding: 10rpx 0rpx;
            border-top: 1px solid #efefef;
            background-color: #fff;
            display: block;
            position: fixed;
            z-index: 999;
            bottom: 0;
            left: 0;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .left {
                font-size: 28rpx;
                color: #000;
                margin-left: 20rpx;

                .money {
                    font-size: 30rpx;
                    color: #f34b4a;
                    font-weight: bold;
                }
            }

            .right {
                width: 20%;
                border-radius: 100rpx;
                color: #fff;
                font-size: 28rpx;
                letter-spacing: 1rpx;
                background: linear-gradient(to right, #f6c489, #ddaa68);
                padding: 20rpx;
                text-align: center;
                margin-right: 20rpx;
            }
        }
    }
</style>